import React, { useState, useEffect } from 'react';
import { Button, Upload } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { DownloadOutlined, CloseOutlined, FileTextOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import { useTRState } from '#/utils/trHooks';
import { export_json_sheets_to_excel } from '@/utils/fileExport';
import { TJModel } from '@/pages/ETrade/components';

import { exportHead_gansu, exportData, _parseFloat } from '../../helper';
import { postImportGansuClearingPriceSurveillance } from '../../services';
import styles from './index.less';

const ImportBtn = (props) => {
  const { disabled, stationId, provinceId } = props;
  const [uploadData, setUploadData] = useState([]);
  const [showBtn, setShowBtn] = useState(true);
  const [fileError, setFileError] = useState(true);
  const [state, setState] = useTRState({
    finalyFile: [], // 最终保存文件
    saveType: 0, // 确认按钮状态
    visible: false, // 导入弹窗展示
    btnLoding: false, // 弹窗确认按钮loding
  });

  useEffect(() => {
    // 文件校验未通过 展示红字提示
    if (!fileError) {
      setUploadData([{ ...uploadData[0], status: 'error', response: '校验未通过' }]);
    }
  }, [fileError]);

  const _beforeUpload = (file) => {
    setFileError(true);
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = async (event) => {
      const { result } = event.target;
      // 以二进制流方式读取得到整份excel表格对象
      const workbook = XLSX.read(result, { type: 'binary', header: 1 });

      for (const sheet in workbook.Sheets) {
        const _temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
        const data = {};
        // 校验首行数据
        if (!_temp?.[0]) {
          TRMessage.warning('请上传正确模板');
          setFileError(false);
          return false;
        }
        _temp.forEach((t) => {
          const date = t['类型'].split(' ').filter((t) => t && t.trim());
          const year_month = moment(date[0], 'MMDD').format('YYYY-MM-DD');
          const hours = date[1].slice(0, 2);
          const minutes = date[1].slice(2, 4);
          const temp = {};
          for (const key in exportData) {
            temp[key] = _parseFloat(t[exportData[key]], 3);
          }
          data[year_month] = {
            ...data[year_month],
            [`${hours}:${minutes}`]: temp,
          };
        });
        setState({
          saveType: 1,
          finalyFile: data,
        });
      }
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file);
    return false;
  };

  const downFile = () => {
    const filename = `模板`;
    const params = {
      list: [],
      name: filename,
      type: 'xlsx',
    };
    params.list = [
      {
        data: [],
        sheetName: '甘肃',
        header: ['类型', ...exportHead_gansu],
      },
    ];

    export_json_sheets_to_excel(params);
  };

  const _uploadChange = (info) => {
    setUploadData(info.fileList);
    if (info.fileList.length) {
      setShowBtn(false);
    } else {
      setState({
        finalyFile: [],
        saveType: 0,
      });
      setShowBtn(true);
    }
  };

  const onImport = () => {
    // 导入数据
    if (disabled) return TRMessage.info('请联系管理员获取相关权限');
    setState({
      visible: true,
    });
  };

  const onClose = () => {
    setState({
      visible: false,
      saveType: 0,
    });
  };

  const importHanldr = async () => {
    if (btnLoding) return;
    setState({
      btnLoding: true,
    });
    const { finalyFile } = state;
    const param = {
      param: finalyFile,
      stationId,
    };
    const res = await postImportGansuClearingPriceSurveillance(param, provinceId);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('导入成功');
      onClose();
    } else {
      TRMessage.error(res?.message || '导入失败');
    }
    setState({
      btnLoding: false,
    });
  };
  const { visible, btnLoding, saveType } = state;
  return (
    <>
      <Button
        style={{ padding: 0 }}
        // className={`${disabled && styles.disabled}`}
        type="link"
        icon={<DownloadOutlined />}
        onClick={onImport}
      >
        导入
      </Button>
      <TJModel
        title={'导入'}
        visible={visible}
        onCancel={onClose}
        footer={[
          <Button key="back" onClick={onClose}>
            取消
          </Button>,
          !!saveType && (
            <Button key="submit" type="primary" loading={btnLoding} onClick={importHanldr}>
              确定
            </Button>
          ),
        ]}
      >
        <div className={styles.content}>
          <div className={styles.label}>
            导入文件
            <span className={styles.after}>仅支持Excel文件</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Upload
              fileList={uploadData}
              name="file"
              onChange={_uploadChange}
              showUploadList={{
                removeIcon: <CloseOutlined style={{ fontSize: 14 }} />,
              }}
              accept=".xls, .xlsx"
              iconRender={() => <FileTextOutlined style={{ color: '#18A0FB' }} />}
              beforeUpload={_beforeUpload}
            >
              {
                <Button
                  style={{ display: !showBtn ? 'none' : 'block' }}
                  className={styles.improt_file}
                  icon={<DownloadOutlined />}
                >
                  导入
                </Button>
              }
            </Upload>
            <div className={styles.down} onClick={downFile}>
              下载模板
            </div>
          </div>
        </div>
      </TJModel>
    </>
  );
};

export default ImportBtn;
